/*
 * @descripttion: user API 路由
 * @author: cp
 * @Date: 2021-04-26 20:43:59
 */

const router = require('koa-router')();
const {
  isExist,
  register,
  loginin,
  changeInfo,
  changePassword,
} = require('../controller/user');
const userValidate = require('../validator/user');
const { loginCheck } = require('../middlewares/loginChecks');
const { genValidator } = require('../middlewares/validator');
router.prefix('/api/user');

// 注册
// genValidator(userValidate)
router.post('/register', async (ctx, next) => {
  const { userName, password, gender } = ctx.request.body;
  ctx.body = await register({ userName, password, gender });
});

// 判断用户名是否存在

router.post('/isExist', async (ctx, next) => {
  const { userName } = ctx.request.body;
  ctx.body = await isExist(userName);
});

// 登录
router.post('/login', async (ctx, next) => {
  const { userName, password } = ctx.request.body;
  ctx.body = await loginin(ctx, userName, password);
});

// 修改密码
// genValidator(userValidate)
router.post('/changePassword', loginCheck, async (ctx, next) => {
  const { newPassword, password } = ctx.request.body;
  const { userName } = ctx.session.userInfo;
  ctx.body = await changePassword({ userName, password, newPassword });
});

// 修改个人信息
router.post(
  '/changeInfo',
  loginCheck,
  genValidator(userValidate),
  async (ctx, next) => {
    const { nickName, city, picture } = ctx.request.body;
    ctx.body = await changeInfo(ctx, { nickName, city, picture });
  }
);

module.exports = router;
